package com.googlecode.slm.web.springweb;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.googlecode.slm.domain.web.TreeBasicAttribute;
import com.googlecode.slm.domain.web.TreeNode;
import com.googlecode.slm.service.TreeService;
import com.googlecode.slm.util.CONSTANTS;
import com.googlecode.slm.web.BasicControler;

@Controller
@RequestMapping(value = "/treemanger")
public class TreeMangerControler extends BasicControler {


	@RequestMapping(value = "/welcome.form")
	public String welcome(){
		return CONSTANTS.VIEWURL_TREEMANGER;
	}
    @Autowired
    @Qualifier(value = "treeService")
    private TreeService treeService;
    
    public TreeService getTreeService() {
		return treeService;
	}

	public void setTreeService(TreeService treeService) {
		this.treeService = treeService;
	}

	@RequestMapping(value="/treeAjax.form")
    @ResponseBody
    public String getTreeForm(int pid){
        List<TreeNode> list = getTreeService().getTreeList(pid);
        JSONArray array = new JSONArray(list, false);
        return array.toString();
    }
	
	@RequestMapping(value="/treeIdAttributeAjax.form")
    @ResponseBody
    public String treeIdAttribute(int id){
		TreeBasicAttribute treeNode = getTreeService().getTreeNode(id);
		JSONObject object = new JSONObject(treeNode);
        return object.toString();
    }
	
	
	@RequestMapping(value="/treeSaveAjax.form")
    @ResponseBody
    public String treeSave(TreeBasicAttribute tree){
		tree.setAvailability(1);
		List<TreeNode> list = getTreeService().saveTree(tree);
//		tree.setId(id);
//		if (id==0){//不成功
//			return "";
//		} else {
//			JSONArray array = new JSONArray();
//			Map map = new HashMap();
//			map.put("id", tree.getId());
//			map.put("text", tree.getName());
//			//map.put("children", value)
//			if (tree.getLeafage()==1)
//				map.put("state", "open");
//			else
//				map.put("state", "closed");
//			array.put(map);
//		}
		if (list!=null){
			JSONArray array = new JSONArray(list, false);
        	return array.toString();
		} else {
			return "";
		}
	}
	
	@RequestMapping(value="/treeDeleteAjax.form")
    @ResponseBody
    public String treeDelete(int id){
		getTreeService().deleteTree(id);
        return "成功";
    }
}
